<?php namespace Common\Model;
use Hdphp\Model\Model;
class Goods extends Model{
//	指定表
	protected $table='goods';
//	自动验证
	protected $validate=array(
	   array('gname','required','商品名称不能为空',3,3),
	   array('price','required','商品价格不能为空',3,3),
//	   array('inventory','required','商品库存不能为空',3,3),
//	   array('listimg','required','商品的列表图片不能为空',3,3),
	);
//	自动完成
	protected $auto=array(
	   array('shelftime','time','function',3,1),
	   array('gnumber','time','function',3,1),
	   array('admin_aid','getAid','method',3,1)
	);
	public function getAid(){
		return $_SESSION['info']['aid'];
	}
	
	public function store(){
		if($this->create()){
			$cid=Q('post.category_cid',0,'intval');
			$cate=new Category;
			$tid=$cate->where("cid=$cid")->pluck('type_tid');
			$this->data['type_tid']=$tid;
						
			$gid=$this->add();
			$goodsAttrModel = new GoodsAtt;
			$detail=new Detail;
			$detail->create();
			$detail->data['goods_gid']=$gid;
			$detail->add();
			
			
//			$this->add();
		//属性添加
		foreach (Q('post.attr') as $taid => $v) {
			if($v){
				$data = array(
					'gvalue'=>$v,
					'typeattribute_tid'=>$taid,
					'goods_gid'=>$gid
				);
				$goodsAttrModel->add($data);
			}
		}
		//规格添加
		$spec = Q('post.spec');
		if($spec){
			$value = $spec['value'];
			foreach ($value as $taid => $v) {
				foreach ($v as $kk => $vv) {
					$data = array(
						'gvalue'=>$vv,
						'typeattribute_tid'=>$taid,
						'goods_gid'=>$gid,
						'addprice'=>$spec['addprice'][$taid][$kk]
					);
					$goodsAttrModel->add($data);
				}
			}
		}
			
			
			return true;
		}
			return false;
	}
	
	
	public function edit(){
		if(!$this->create()) return false;
		$gid=Q('post.gid',0,'intval');
		$this->create();
//		p($this->data);exit;
		$this->save();
		$detail=new Detail;
		$detail->create();
		$detail->where("goods_gid={$gid}")->save();
		
		
		$goodsAttr=new GoodsAtt;
		
		$goodsAttr->where("goods_gid={$gid}")->delete();
		
		$attr=Q('post.attr');
		//属性添加
		foreach (Q('post.attr') as $taid => $v) {
			if($v){
				$data = array(
					'gvalue'=>$v,
					'typeattribute_tid'=>$taid,
					'goods_gid'=>$gid
				);
				$goodsAttr->add($data);
			}
		}
//		规格添加
		$spec = Q('post.spec');
		if($spec){
			$value = $spec['value'];
			foreach ($value as $taid => $v) {
				foreach ($v as $kk => $vv) {
					$data = array(
						'gvalue'=>$vv,
						'typeattribute_tid'=>$taid,
						'goods_gid'=>$gid,
						'addprice'=>$spec['addprice'][$taid][$kk]
					);
					$goodsAttr->add($data);
				}
			}
		}
		return true;
	}
}
